﻿using Syncfusion.UI.Xaml.Grid;
using Syncfusion.UI.Xaml.Grid.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace Syncfusion.Lib.Controls
{
    /// <summary>
    /// <see cref="SfDataGrid"/> 搜索助手类
    /// </summary>
    public class SfDataGirdSearchHelper:SearchHelper
    {
        /// <summary>
        /// 在创建新实例时调用。
        /// </summary>
        /// <param name="sfDataGrid"></param>
        public SfDataGirdSearchHelper(SfDataGrid sfDataGrid):base(sfDataGrid)
        {

        }


        /// <summary>
        /// 在单元格的 TextBlock 中查找搜索文本，并调用 ApplyInline 方法设置搜索文本的背景颜色
        /// </summary>
        /// <param name="column">表示与单元格关联的 GridColumn 列对象</param>
        /// <param name="record">表示与单元格关联的数据对象</param>
        /// <param name="ApplySearchHighlightBrush">表示是否应用 SearchBrush 和 SearchHighlightBrush 画刷</param>
        /// <returns></returns>
        protected override bool SearchCell(DataColumnBase column, object record, bool ApplySearchHighlightBrush)
        {
            if (string.IsNullOrEmpty(column?.GridColumn?.MappingName))
            {
                return false;
                //throw new InvalidOperationException("To get the search value, the MappingName property of columns should not be empty.");
            }
            return base.SearchCell(column, record, ApplySearchHighlightBrush);            
        }

        /// <summary>
        /// 筛选记录
        /// </summary>
        /// <param name="dataRow"></param>
        /// <returns></returns>
        protected override bool FilterRecords(object dataRow)
        {
            if (string.IsNullOrEmpty(SearchText))
            {
                return true;
            }

            if (Provider == null)
            {
                Provider = DataGrid.View.GetPropertyAccessProvider();
            }

            for (int i = DataGrid.ResolveToGridVisibleColumnIndex(DataGrid.GetFirstColumnIndex()); i < DataGrid.Columns.Count; i++)
            {
                GridColumn gridColumn = DataGrid.Columns[i];
                if (gridColumn != null && gridColumn.ActualWidth != 0.0 && !gridColumn.IsHidden && MatchSearchText(gridColumn, dataRow))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
